package isae.c2.android.depense;

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import isae.c2.android.depense.DB.TransactionDBAdapter;
import isae.c2.android.depense.DB.CategoryDBAdapter;

public class New_Transaction extends Activity {
	/** * les variables qui correspondent aux elements qui se trouvent sur l'ecran*/
	private EditText mMontant;
	private Spinner mCategory;
	private EditText mDescription;
	private Long mRowId;
	private TransactionDBAdapter mDbHelper;
	private CategoryDBAdapter mDbCategory;
	private Cursor cursor;
	private Integer mSave1;
	private static final int ACTIVITY_CREATE = 0;
	
	private TextView mDateDisplay;
    private Button mPickDate;
    private int mYear;
    private int mMonth;
    private int mDay;

    static final int DATE_DIALOG_ID = 0;
    
	@Override
	protected void onCreate(Bundle bundle) {
		mSave1=1;
		super.onCreate(bundle);
		mDbHelper = new TransactionDBAdapter(this);
		mDbHelper.open();
		setContentView(R.layout.new_transaction);
		
		mMontant = (EditText) findViewById(R.id.new_Montant);
		mCategory = (Spinner) findViewById(R.id.spinner1);
		mDescription = (EditText) findViewById(R.id.new_Description);

		Button confirmButton = (Button) findViewById(R.id.todo_new_button);
		mRowId = null;
		Bundle extras = getIntent().getExtras();
		mRowId = (bundle == null) ? null : (Long) bundle
				.getSerializable(TransactionDBAdapter.KEY_ROWID);
		if (extras != null) {
			mRowId = extras.getLong(TransactionDBAdapter.KEY_ROWID);
		}
		
        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
        mPickDate = (Button) findViewById(R.id.pickDate);

        /** * quand on clique sur le bouton "Changer la date"*/
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        /** * initialiser la valeur de la date avec la date du systeme*/
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        /** * initialiser la date*/
        updateDisplay();
        
        /** * remplir la liste des categories*/
		fillCategory();
		
		/** * Si cette page ouvre de la page liste, lire les donnees cnvenables et les afficher*/
		populateFields();
		
		/** * Quand on clique sur le bouton enregistrer*/
		confirmButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				mSave1 = 0; 
				setResult(RESULT_OK);
				finish();
			}

		});
	}
	
	/** * Si cette page ouvre de la page liste, lire les donnees cnvenables et les afficher*/
	private void populateFields() {
		if (mRowId != null) {
			Cursor todo = mDbHelper.fetchTrx(mRowId);
			startManagingCursor(todo);
			
			long category = todo.getLong(todo
					.getColumnIndexOrThrow(TransactionDBAdapter.KEY_CAT));
			
			for (int i = 0; i < mCategory.getCount(); i++) {

				long s = (long) mCategory.getItemIdAtPosition(i);
				
				if (s==category) {
					mCategory.setSelection(i);
				}
			}
			
			mDateDisplay.setText(todo.getString(todo
					.getColumnIndexOrThrow(TransactionDBAdapter.KEY_DATE)));
			
			mMontant.setText(todo.getString(todo
					.getColumnIndexOrThrow(TransactionDBAdapter.KEY_AMOUNT)));
			
			mDescription.setText(todo.getString(todo
					.getColumnIndexOrThrow(TransactionDBAdapter.KEY_DESCRIPTION)));
		}
	}
	
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		saveState();
		outState.putSerializable(TransactionDBAdapter.KEY_ROWID, mRowId);
	}

	@Override
	protected void onPause() {
		super.onPause();
		
		if (mSave1==0) {
			saveState();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
	}

	private void saveState() {
		String date =  mDateDisplay.getText().toString();
		String montant = mMontant.getText().toString();
		Long category = mCategory.getSelectedItemId();
		String description = mDescription.getText().toString();
		
		if (!date.equals("")  && !montant.equals("") && !category.equals("")  && !description.equals("")) {
			if (mRowId == null){
				
					long id = mDbHelper.createTrx(date, description, montant, category);
					if (id > 0) {
						mRowId = id;
					}
			} else {
				mDbHelper.updateTrx(mRowId, date, description, montant, category);
			}
		}
	}
	
	/** * remplir la liste des categories*/
	private void fillCategory() {
		Spinner catSpinner = (Spinner) findViewById(R.id.spinner1);
		mDbCategory = new CategoryDBAdapter(this);
		mDbCategory.open();
		cursor = mDbCategory.fetchAllTodos();
		startManagingCursor(cursor);

		String[] from = new String[] { CategoryDBAdapter.KEY_CODE };
		int[] to = new int[] {R.id.label};

		/** * remplir la liste*/
		SimpleCursorAdapter catAdapter = new SimpleCursorAdapter(this,
				R.layout.todo_row, cursor, from, to);
		catSpinner.setAdapter(catAdapter);
		}
	
	/** * mettre a jour la date lu de la base de donnees*/
    private void updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" "));
    }
    
    /** * quand l'utilisateur choisi la date a partir du bouton*/
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };
      
            @Override
            protected Dialog onCreateDialog(int id) {
                switch (id) {
                case DATE_DIALOG_ID:
                    return new DatePickerDialog(this,
                                mDateSetListener,
                                mYear, mMonth, mDay);
                }
                return null;
            }
            
            /** * quand l'utilisateur clique le bouton "menu", 
             	* cela lui permet de creer une nouvelle categorie*/
        	@Override
        	public boolean onCreateOptionsMenu(Menu menu) {
        		MenuInflater inflater = getMenuInflater();
        		inflater.inflate(R.menu.cat_listmenu, menu);
        		return true;
        	}
        	
        	@Override
        	public boolean onOptionsItemSelected(MenuItem item) {
        		switch (item.getItemId()) {
        		case R.id.insert:
        			createTodo();
        			return true;
        		}
        		return super.onOptionsItemSelected(item);
        	}
        	
        	private void createTodo() {
        		Intent i = new Intent(this, create_category.class);
        		startActivityForResult(i, ACTIVITY_CREATE);
        	}

}
